package cn.itsource.pethome.Basic.service.Impl;

import cn.itsource.pethome.user.constant.PhoneConstant;
import cn.itsource.pethome.Basic.service.IVerificationCodeService;
import cn.itsource.pethome.Basic.util.AjaxResult;
import cn.itsource.pethome.Basic.util.RedisUtils;
import cn.itsource.pethome.Basic.util.SendMessageCode;
import cn.itsource.pethome.Basic.util.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {
    @Override
    public AjaxResult sendPhoneCode(String phone) {
       //从redis获取验证码   uht5:123243342
        String value = RedisUtils.INSTANCE.get(PhoneConstant.PHONE_REG + ":" + phone);
        //随机产生验证码
        String code = StrUtils.getComplexRandomString(4);
        //判断redis验证码是否过期
       if(StringUtils.isNotBlank(value)){
            //截取获取验证码时间戳
            String split = value.split(":")[1];
            //获取当前时间毫秒数
            long currentTimeMillis = System.currentTimeMillis();
            if(currentTimeMillis-Long.valueOf(split)<60*1000){
                return new AjaxResult(false,"请不要在一分钟内多次发送");
            }
            //覆盖当前随机产生验证码
            code=value.split(":")[0];
        }
        //将验证码存入redis
        RedisUtils.INSTANCE.set(PhoneConstant.PHONE_REG +":"+phone,code+":"+System.currentTimeMillis(),5*60);
        String text = "尊敬的用户，你的验证码是："+code+"请在5分钟内操作完成";
        System.out.println("========="+text);
        SendMessageCode.sendPhoneCode(phone,text);
        return new AjaxResult();
    }
}
